package com.wbao.dianniu.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.im.NotificationInitSampleHelper;
import com.wbao.dianniu.im.UserProfileSampleHelper;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.listener.ILoginSMSCodeListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.manager.LoginSMSCodeManager;
import com.wbao.dianniu.utils.KeyboardHeightHandler;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

/**
 * 短信验证码登录
 * <p>
 * Created by yejianjun on 2017/11/7.
 */

public class MsgLoginActivity extends BaseActivity implements ILoginSMSCodeListener, ILoginListener {

    private static final String TAG = MsgLoginActivity.class.getSimpleName();
    private Button loginBtn;
    private TextView authCodeTV;
    private EditText mobileEditText;
    private EditText authCdoeEditText;
    private int count = 0;
    private LoginManager manager;
    private LoginSMSCodeManager smsCodeManager;
    private YWIMKit mIMKit;
    private Dialog pDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }*/
        setContentLayout(R.layout.activity_message_login, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(R.string.message_login);
        initView();
        initData();
        if (0 == SharedPreferencesUtils.getKeyboardHeight(this)) {
            KeyboardHeightHandler handler = new KeyboardHeightHandler();
            handler.getKeyboardHeight(this);
        }
    }

    private void initView() {
        loginBtn = (Button) findViewById(R.id.msg_login_btn);
        authCodeTV = (TextView) findViewById(R.id.msg_login_authCode);
        mobileEditText = (EditText) findViewById(R.id.msg_login_mobile);
        authCdoeEditText = (EditText) findViewById(R.id.msg_login_code);
        authCodeTV.setOnClickListener(this);
        loginBtn.setOnClickListener(this);
    }

    private void initData() {
        manager = new LoginManager(this);
        manager.addLoginListener(this);
        smsCodeManager = new LoginSMSCodeManager(this);
        smsCodeManager.addLoginSmsCodeListener(this);
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            authCodeTV.setText(millisUntilFinished / 1000 + getResources().getString(R.string.auth_code_get_desc));
        }

        @Override
        public void onFinish() {
            authCodeTV.setEnabled(true);
            authCodeTV.setText(getResources().getString(R.string.register_get_auth_password));
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        if (null != timer) {
            timer.cancel();
        }
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeLoginListener(this);
        }
        if (null != smsCodeManager) {
            smsCodeManager.removeLoginSmsCodeListener(this);
        }
    }

    ;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        String mobile = mobileEditText.getText().toString().trim();
        String authCode = authCdoeEditText.getText().toString().trim();
        switch (v.getId()) {
            case R.id.msg_login_btn:
                if (authMobile(mobile)) {
                    if (count > 5) {
                        Notification.toast(this, getResources().getString(R.string.register_error_5_toast));
                        return;
                    }
                    showWaittingDialog();
                    manager.Login(MsgLoginActivity.this, mobile, null, Utils.getDeviceId(this), null, null, Utils.getVersionName(MsgLoginActivity.this), authCode);
                }
                break;
            case R.id.msg_login_authCode:
                //获取验证码
                if (authMobile(mobile)) {
                    /** 每次获取验证码，清除错误累计 */
                    count = 0;
                    v.setEnabled(false);
                    authCodeTV.setBackgroundResource(R.drawable.get_code_unpress);
                    timer.start();
                    smsCodeManager.getLoginSmsCode(mobile);
                }
                break;
            default:
                break;
        }


    }

    private boolean authMobile(String mobile) {
        boolean ret = false;
        if (null == mobile) {
            toastString(getResources().getString(R.string.register_error_1));
            return ret;
        } else {
            boolean ismobile = mobile.matches("^(13|15|18|14|17)\\d{9}$");
            if (ismobile) {
                ret = true;
            } else {
                toastString(getResources().getString(R.string.login_error_1));
            }
            return ret;
        }
    }

    private void toastString(String message) {
        Notification.toast(MsgLoginActivity.this, message);
    }

    @Override
    public void onLoginSmsFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onLoginSmsSuccess() {

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        toastString(errorMsg == null ? "" : errorMsg);
        count++;
    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        /** 清除登录错误次数累加	*/
        SharedPreferencesUtils.setLoginErrorCount(0);
        Utils.saveLoginData(this,objdata);
        init(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), getResources().getString(R.string.app_key));
        //登录成功时，登录IM
        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getAccountInfo().getPwd());
    }

    private void init(String userId, String appKey) {
        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
            LoginSampleHelper.getInstance().loginOut_Sample();
        }
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();
    }

    private void saveConfigInfo(String pwd) {
        SharedPreferencesUtils.init(MsgLoginActivity.this);
        SharedPreferencesUtils.setUserName(mobileEditText.getText().toString());
        SharedPreferencesUtils.setPassword(pwd);
        SharedPreferencesUtils.setAutoLoginStatus(true);
    }

    public void loginIM(String userId, final String password) {
        if (null == LoginSampleHelper.getInstance().getIMKit()) {
            //初始化imik
            LoginSampleHelper.getInstance().initIMKit(userId, getResources().getString(R.string.app_key));
        }
        mIMKit = LoginSampleHelper.getInstance().getIMKit();
//        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
//        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
//            LoginSampleHelper.getInstance().loginOut_Sample();
//        }
        //开始登录
        if (null == mIMKit) {
            Log.d(TAG, "im system init error ");
            return;
        }
//        Log.d(TAG, "开始登录IM：" + System.currentTimeMillis() + "");
        IYWLoginService loginService = mIMKit.getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userId, password);
        loginService.login(loginParam, new IWxCallback() {

            @Override
            public void onSuccess(Object... arg0) {
//                Log.d(TAG, "登录成功IM：" + System.currentTimeMillis() + "");
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                // 保存自动登录配置信息
                saveConfigInfo(password);
                // 成功 界面跳转
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setClass(MsgLoginActivity.this, MainActivity.class);
                startActivity(intent);
                MsgLoginActivity.this.finish();
            }

            @Override
            public void onProgress(int arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onError(int errCode, String description) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
                if (null != description) {
                    Notification.toast(MsgLoginActivity.this, description);
                } else {
                    Notification.toast(MsgLoginActivity.this, "【登录失败，错误码】：" + errCode);
                }

            }
        });
    }

    private void showWaittingDialog() {
        pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
        pDialog.show();
    }

}
